package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import dataprocess.DataProcessor;
import utils.Config;

public class TCPListener implements Runnable {

    private static final Logger logger = LogManager.getLogger(TCPListener.class);
    
    private Config config;
    private Socket incoming;

    public TCPListener(Config config, Socket incoming) {
        this.config = config;
        this.incoming = incoming;
    }

    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));) {
            char[] buf = new char[1024];
            in.read(buf, 0, buf.length);
            InetAddress address = incoming.getInetAddress();
            int port = incoming.getPort();
            String data = new String(buf).trim();
            System.out.println("Received data:[" + data + "] from address:" + address + " at port: " + port);
            logger.info("Received data:[" + data + "] from address:" + address + " at port: " + port);
            if (!data.isEmpty()) {
                processData(data, config);
            }
        } catch (IOException e) {
            logger.error(e);
        }
    }

    private void processData(String data, Config config) {
        switch (config.getType()) {
        case "iueuav":
            DataProcessor.iueUAVMonitorDataProcess(data, config);
            break;
        case "iuewind":
            DataProcessor.iueWindDataProcess(data, config);
            break;
        case "iuesuperstation":
            DataProcessor.iueSuperStationProcess(data, config);
        default:
            break;
        }

    }

}
